package presenter;

import java.util.Observable;
import java.util.Observer;

import model.base.Model;
import model.base.MyModel;
import model.base.Solution;
import view.MyConsoleView;
import view.View;

public class Presenter implements Observer {		// The presenter - is an ovserver
	private View vi;								// holds instances of view and model
	private Model mo;
	private UserCommands commands;					//  an instance of UserComands - enable to operate commands through it
	
	public Presenter(Model mod, View view) {	// C'tor - init variables
		this.mo = mod;
		this.vi = view;
		this.commands = new UserCommands();
	}
	
	@Override
	public void update(Observable obAble, Object arg1) {		// operates everytime the observers gets notifications on changes of observables
		if (obAble == mo){
			Solution solution = mo.getSolution();				// operates getSolution and displaySolution
			vi.displaySolution(solution);			
		}
		else if (obAble == vi){
			String action = vi.getUserAction();					//Takse the userAction (input) - splits it to 2 parts : before and after the space 
			String[] StringArray = action.split(" ");			
			String commandString = StringArray[0];
			String a = null;
			if (StringArray.length>1)
				a = StringArray[1];								// and sends the splited data as parameters to the UserCommands "commands" instance in order to do the user actual command's
			commands.doCommand(mo, commandString, a);
		}
	}
	
	public static void main(String[] args) {					//   Main!
		MyModel model = new MyModel();
		MyConsoleView view = new MyConsoleView();
		Presenter presenter = new Presenter(model, view);
		
		model.addObserver(presenter);							// sets the presenter as an observer of the 2 observables - view and model
		view.addObserver(presenter);
		
		view.start();											// kicks the observable view to start its main routine
	}
	

}
